<template>
  <div class="add-product-wrapper">
    <div class="add-product-card">
      <h2>添加商品</h2>
      <form @submit.prevent="submitForm" class="product-form">
        <!-- 商品名称（必填） -->
        <div class="form-group">
          <label for="productName">商品名称 *</label>
          <input
              type="text"
              id="productName"
              v-model="formData.foodName"
              placeholder="请输入商品名称"
              required
              maxlength="100"
          />
        </div>

        <!-- 商品价格（必填） -->
        <div class="form-group">
          <label for="productPrice">商品价格 *</label>
          <input
              type="number"
              step="0.01"
              id="productPrice"
              v-model.number="formData.foodPrice"
              placeholder="请输入商品价格"
              required
              min="0.01"
          />
        </div>

        <!-- 商品描述（可选） -->
        <div class="form-group">
          <label for="productDescription">商品描述</label>
          <input
              type="text"
              id="productDescription"
              v-model="formData.foodExplain"
              placeholder="请输入商品描述（可选）"
          />
        </div>

        <!-- 商品图片链接（可选） -->
        <div class="form-group">
          <label for="productImage">商品图片链接</label>
          <input
              type="url"
              id="productImage"
              v-model="formData.foodImg"
              placeholder="请输入图片链接（可选）"
          />
        </div>

        <!-- 店铺ID（必填） -->
        <div class="form-group">
          <label for="businessId">店铺ID *</label>
          <input
              type="number"
              id="businessId"
              v-model.number="formData.business.id"
              placeholder="请输入店铺ID"
              required
              min="1"
          />
        </div>

        <!-- 备注（可选） -->
        <div class="form-group">
          <label for="remarks">备注</label>
          <input
              type="text"
              id="remarks"
              v-model="formData.remarks"
              placeholder="请输入备注（可选）"
          />
        </div>

        <!-- 提交与取消按钮 -->
        <div class="button-group">
          <button type="button" class="cancel-btn" @click="goBack">取消</button>
          <button type="submit" class="submit-btn" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : '添加商品' }}
          </button>
        </div>

        <!-- 消息提示 -->
        <p v-if="message" :class="['message', message.type]">{{ message.text }}</p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

// 表单数据对象
const formData = ref({
  foodName: '',          // 必填
  foodExplain: '',       // 可选
  foodImg: '',           // 可选
  foodPrice: null,       // 必填，数字
  remarks: '',           // 可选
  business: {            // 必填
    id: null             // 必填，店铺ID
  }
})

// 提交状态
const isSubmitting = ref(false)

// 消息提示
const message = ref(null)

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 提交表单
const submitForm = async () => {
  message.value = null

  // 必填校验
  if (!formData.value.foodName.trim()) {
    message.value = { type: 'error', text: '请输入商品名称！' }
    return
  }
  if (formData.value.foodPrice === null || formData.value.foodPrice <= 0) {
    message.value = { type: 'error', text: '请输入有效的商品价格！' }
    return
  }
  if (formData.value.business.id === null || formData.value.business.id <= 0) {
    message.value = { type: 'error', text: '请输入有效的店铺ID！' }
    return
  }

  try {
    isSubmitting.value = true

    // 获取 JWT Token
    const token = sessionStorage.getItem('jwt')
    if (!token) {
      message.value = { type: 'error', text: '用户未登录！' }
      return
    }

    // 构造请求体
    const payload = {
      foodName: formData.value.foodName,
      foodExplain: formData.value.foodExplain,
      foodImg: formData.value.foodImg,
      foodPrice: formData.value.foodPrice,
      remarks: formData.value.remarks,
      business: {
        id: formData.value.business.id
      }
    }

    // 发送 POST 请求
    const response = await axios.post('/foods', payload, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token.slice(1,-1)}`
      }
    })

    if (response.status === 200 || response.status === 201) {
      message.value = { type: 'success', text: '商品添加成功！' }
      // 重置表单（保留business.id）
      formData.value = {
        ...formData.value,
        foodName: '',
        foodExplain: '',
        foodImg: '',
        foodPrice: null,
        remarks: ''
      }
      // 3秒后自动返回
      setTimeout(() => {
        router.go(-1)
      }, 3000)
    }
  } catch (err) {
    console.error('添加商品失败:', err)

    if (err.response) {
      // 服务器返回错误信息
      const errorMsg = err.response.data?.message || '添加商品失败'
      message.value = { type: 'error', text: errorMsg }
    } else if (err.request) {
      message.value = { type: 'error', text: '网络错误，请检查连接！' }
    } else {
      message.value = { type: 'error', text: '添加商品失败，请重试！' }
    }
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.add-product-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.add-product-card {
  width: 100%;
  max-width: 600px;
  padding: 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 24px;
}

.product-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  font-weight: bold;
  color: #555;
}

input {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  outline: none;
  border-color: #007bff;
}

/* 数字输入框样式 */
input[type="number"] {
  -moz-appearance: textfield;
}

input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* 按钮样式 */
.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.submit-btn {
  flex: 1;
  padding: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.submit-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.cancel-btn {
  flex: 1;
  padding: 12px;
  background-color: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

/* 消息提示样式 */
.message {
  margin-top: 15px;
  padding: 12px;
  border-radius: 6px;
  text-align: center;
  font-size: 14px;
}

.message.success {
  background-color: #e6ffed;
  color: #1a7324;
  border: 1px solid #b7eb8f;
}

.message.error {
  background-color: #ffebee;
  color: #c62828;
  border: 1px solid #ffa4a4;
}
</style>